package com.jhgsys.internal.formDesign.service.impl;

import com.jhgsys.internal.formDesign.dto.FormDesignDto;
import com.jhgsys.internal.formDesign.dto.FormFillDto;
import com.jhgsys.internal.formDesign.entity.FormFill;
import com.jhgsys.internal.formDesign.mapper.FormFillMapper;
import com.jhgsys.internal.formDesign.service.IFormDesignService;
import com.jhgsys.internal.formDesign.service.IFormFillService;
import com.jhgsys.internal.common.entity.QueryRequest;
import com.jhgsys.internal.common.utils.FebsUtil;
import com.jhgsys.internal.formDesign.service.IFormPublishObjectService;
import com.jhgsys.internal.system.entity.Tenant;
import com.jhgsys.internal.system.service.ITenantService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.annotation.Propagation;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.toolkit.StringPool;

import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 表单填报 Service实现
 *
 * @author zhangwei
 * @date 2024-09-05 08:53:07
 */
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class FormFillServiceImpl extends ServiceImpl<FormFillMapper, FormFill> implements IFormFillService {

    @Autowired
    private IFormDesignService formDesignService;

    @Autowired
    private ITenantService tenantService;

    /**
     * 查询（分页）
     * @author zhangwei
     * @date 2024-09-05 08:53:07
     * @param request QueryRequest
     * @param formFill formFill
     * @return IPage<FormFill>
    */
    @Override
    public IPage<FormFill> findFormFillPage(QueryRequest request, FormFill formFill) {
        LambdaQueryWrapper<FormFill> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(FormFill::getDeletedFlg, 0);
        // TODO 设置查询条件

        Page<FormFill> page = new Page<>(request.getPageNum(), request.getPageSize());
        FebsUtil.pageWrapper(page, request);
        return this.page(page, queryWrapper);
    }

    /**
     * 查询录入历史（分页）
     * @author zhangwei
     * @date 2024-09-05 08:53:07
     * @param request QueryRequest
     * @param formFill formFill
     * @return IPage<FormFill>
     */
    @Override
    public IPage<FormFill> findFormFillRecordPage(QueryRequest request, FormFill formFill) {
        Page<FormFill> page = new Page<>(request.getPageNum(), request.getPageSize());

        IPage<FormFill>  pageinfo = this.baseMapper.selectFormFillPage(page,formFill);
        return pageinfo;
    }
    /**
     * 查询（所有）
     * @author zhangwei
     * @date 2024-09-05 08:53:07
     * @param formFill formFill
     * @return List<FormFill>
     */
    @Override
    public List<FormFill> findFormFillList(FormFill formFill) {
	    LambdaQueryWrapper<FormFill> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(FormFill::getDeletedFlg, 0);
		// TODO 设置查询条件
		return this.baseMapper.selectList(queryWrapper);
    }

    /**
    * 根据ID查询
    * @author zhangwei
    * @date 2024-09-05 08:53:07
    * @param id
    * @return FormFill
    */
    @Override
    public FormFill findFormFillById(String id){
        return this.baseMapper.selectById(id);
    }

    /**
     * 新增
     * @author zhangwei
     * @date 2024-09-05 08:53:07
     * @param formFillDto formFill
     */
    @Override
    @Transactional
    public void createFormFill(FormFillDto formFillDto) {
        formFillDto.setCreatedTime(new Date());
        String no = this.createFormFillNo(formFillDto.getTenantId());
        formFillDto.setFillNo(no);
        if(StringUtils.isNotBlank(formFillDto.getSubmitFlg()) && "1".equals(formFillDto.getSubmitFlg())){
            formFillDto.setStatus("1");
        }else if( StringUtils.isNotBlank(formFillDto.getSubmitFlg()) && "2".equals(formFillDto.getSubmitFlg())){
            formFillDto.setStatus("2");
        }
        this.save(formFillDto);
    }
    /**
     * 获取隐患信息编号
     * @param tenantId
     * @return
     */
    @Override
    public String createFormFillNo(String tenantId) {
        String no = "";
        String tenantCode = "";
        Tenant tenant = tenantService.getById(tenantId);
        if(null != tenant){
            tenantCode = tenant.getTenantCode();
        }
        FormFill formFill = this.baseMapper.selectOne(
                new LambdaQueryWrapper<FormFill>().eq(FormFill::getTenantId,tenantId)
                        .orderByDesc(FormFill::getCreatedTime).last("limit 1"));
        no = Calendar.getInstance().get(Calendar.YEAR) + tenantCode;
        if(null != formFill){
            //在最新的编号上+1
            String currentNewestNo = formFill.getFillNo().substring(formFill.getFillNo().length()-5);
            no += String.format("%05d",Integer.parseInt(currentNewestNo)+1);
        }
        return no;
    }
    /**
     * 修改
     * @author zhangwei
     * @date 2024-09-05 08:53:07
     * @param formFillDto formFill
     */
    @Override
    @Transactional
    public void updateFormFill(FormFillDto formFillDto) {
        if(StringUtils.isNotBlank(formFillDto.getSubmitFlg()) && "1".equals(formFillDto.getSubmitFlg())){
            formFillDto.setStatus("1");
        }else if( StringUtils.isNotBlank(formFillDto.getSubmitFlg()) && "2".equals(formFillDto.getSubmitFlg())){
            formFillDto.setStatus("2");
        }
        formFillDto.setUpdatedTime(new Date());
        this.saveOrUpdate(formFillDto);
    }

    /**
     * 逻辑删除
     * @author zhangwei
     * @date 2024-09-05 08:53:07
     * @param formFill formFill
     * @param formFillIds formFillIds
     */
    @Override
    @Transactional
    public void deleteFormFill(FormFill formFill,String formFillIds) {
        List<String> list = Arrays.asList(formFillIds.split(StringPool.COMMA));
        this.baseMapper.update(formFill,new LambdaQueryWrapper<FormFill>().in(FormFill::getRegisterId,list));
	}

    /**
    * 物理删除
    * @author zhangwei
    * @date 2024-09-05 08:53:07
    * @param formFillIds formFillIds
    */
    @Override
    @Transactional
    public void physicallyDeleteFormFill(String formFillIds) {
        List<String> list = Arrays.asList(formFillIds.split(StringPool.COMMA));
        LambdaQueryWrapper<FormFill> wapper = new LambdaQueryWrapper<>();
        wapper.in(FormFill::getRegisterId,list);
        this.remove(wapper);
    }
}
